from flask import current_app
from flask import render_template, redirect, g, jsonify
from flask import request
from flask import session
from info import db,constants
from info.models import User, Category, News
from info.moduls.profile import profile_bp
from info.utils.common import get_user_info
from info.utils.response_code import RET
from info.utils.pic_storge import pic_storge

@profile_bp.route("/news_list")
@get_user_info
def news_list():
    """新闻列表接口"""
    user = g.user
    # 获取参数 当前传上来的页码
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except Exception as e:
        page = 1
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news_li = []
    current_page = 1
    total_page = 1
    # 查询新闻数据
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_li = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户发布的新闻异常")

    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "current_page": current_page,
        "total_page": total_page,
    }

    return render_template("user_news_list.html", data=data)


@profile_bp.route("/news_release", methods=["GET", "POST"])
@get_user_info
def news_release():
    """新闻发布接口"""

    if request.method == "GET":
        categorys = Category.query.all()
        category_li = []
        for category in categorys:
            category_li.append(category.to_dict())
        # 移除最新分类
        category_li.pop(0)
        data = {
            "categories": category_li
        }
        return render_template("user_news_release.html", data=data)

    # 1.获取参数
    # 新闻标题
    title = request.form.get("title")
    # 新闻来源
    source = "个人发布"
    # 新闻摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 主图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")
    # 2.校验参数
    # 2.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3.逻辑处理
    # 3.1存储图片到七牛云
    try:
        index_image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="获取图片数据异常")

    try:
        url = pic_storge(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="七牛云上传图片异常")

    # 3.2创建新闻模型
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + url
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    # 3.3将新闻模型添加到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存新闻模型到数据库异常")

    # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="发布新闻成功")


# 127.0.0.1:5000/user/collection?p=2
@profile_bp.route("/collection")
@get_user_info
def user_collection():
    """用户收藏列表"""
    # 获取用户对象
    user = g.user
    # 获取参数 当前传上来的页码
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    collections = []
    current_page = 1
    total_page = 1
    # 数据库查询该用户收藏的新闻，已经分页处理
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        collections = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        jsonify(errno=RET.DBERR, errmsg="查询用户收藏新闻列表数据库异常")

    # 将模型对象转换成新闻字典
    collection_dict_li = []
    for collection in collections:
        collection_dict_li.append(collection.to_basic_dict())

    data = {
        "collections": collection_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("user_collection.html", data=data)


@profile_bp.route("/pass_info", methods=["GET", "POST"])
@get_user_info
def pass_info():
    """显示修改密码界面/修改密码后端接口"""
    # 获取用户对象
    user = g.user
    if request.method == "GET":
        return render_template("user_pass_info.html")

    # 1.接受参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 2.校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.逻辑处理
    # 3.1 验证旧密码是否正确
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="旧密码错误")

    # 3.2 将新密码进行赋值
    user.password = new_password

    # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="修改用户密码成功")



@profile_bp.route("/pic_info", methods=["GET", "POST"])
@get_user_info
def pic_info():
    """显示图片界面/上传图片接口"""
    # 获取用户对象
    user = g.user
    if request.method == "GET":
        return render_template("user_pic_info.html")

    # 1.接受参数
    try:
        avatar_data = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取图片参数错误")

    # 2.调用封装好的工具 将图片上传到七牛云
    try:
        url = pic_storge(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方七牛云报错图片失败")
    # 3、将图片到用户模型avatar_url属性中
    user.avatar_url = url

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="报错用户头像url到数据库失败")

    # 拼接完整url
    full_url = constants.QINIU_DOMIN_PREFIX + url
    # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="修改用户头像成功",data={"avatar_url": full_url})






# 127.0.0.1:5000/user/base_info
@profile_bp.route("/base_info", methods=["GET", "POST"])
@get_user_info
def user_base_info():
    # 获取用户数据
    user = g.user
    if request.method == "GET":
        return render_template("user_base_info.html", data=g.user.to_dict())

    # 修改用户基本资料
    # 1.获取参数
    paramdit = request.json
    nick_name = paramdit.get("nick_name")
    signatrue = paramdit.get("signature")
    gender = paramdit.get("gender")
    # 2.校验参数


    if not all([nick_name, signatrue, gender]):
        return jsonify(errno=RET.NODATA, errmsg="数据不能为空")
    if gender not in ["WOMAN", "MAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.逻辑处理
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signatrue

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据到数据库异常")

    # 更新session里面的nick_name数据
    session["nick_name"] = nick_name

    # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="修改用户基本资料成功")






# 127.0.0.1:5000/user/info
@profile_bp.route("/info")
@get_user_info
def user_info():
    # 1.获取用户数据
    user = g.user
    if not user:
        redirect("/")

    data = {
        "user": user.to_dict() if user else None,
    }
    return render_template("user.html", data=data)

